package cn.iune.erp.customer;

import java.sql.SQLException;
import java.text.ParseException;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.justep.baas.Utils;
import com.justep.baas.data.Row;
import com.justep.baas.data.RowState;
import com.justep.baas.data.Table;
import com.justep.baas.data.Transform;

@Transactional
@Service
public class FileCustomerAddressServiceImpl implements IFileCustomerAddressService {
	
	private final Logger log = LogManager.getLogger(this);

	@Autowired
	private IFileCustomerAddressDao dao;
	
	public FileCustomerAddressServiceImpl(){
		
	}
	@Override
	public void insert(FileCustomerAddress obj) {
		dao.insert(obj);
	}
	
	@Transactional
	@Override
	public void delete(String fID) {
		dao.delete(fID);
	}
	
	@Transactional
	@Override
	public void update(FileCustomerAddress obj) {
		// TODO Auto-generated method stub
		dao.update(obj);
	}	
	
	@Transactional
	@Override
	public void delete(JSONObject data) {
		JSONArray ids = data.getJSONArray("ids");
		for(int i=0;i<ids.size();i++){
			String id = ids.getString(i);
			dao.delete(id);
		}
	}
	
	@Override
	public FileCustomerAddress getByID(String fID) {
		return dao.getByID(fID);
	}
	@Override
	public List<FileCustomerAddress> getAll(){
		return dao.getAll();
	}
	
	@Override
	public FileCustomerAddress getByNo(String fAddressName, String factoryID) {
		return dao.getByNo(fAddressName, factoryID);
	}
	
	@Transactional
	@Override
	public JSONObject save(JSONObject object) throws ParseException {
		// TODO Auto-generated method stub
		// JSON转换Table
		Table table = Transform.jsonToTable(object);
		
		JSONObject data = new JSONObject();
		data.put("concept", table.getTableName());
		JSONArray rows = new JSONArray();
		
		List<Row> list = table.getRows();
		for(Row row : list){
			JSONObject javaObject= Transform.rowToJavaObject(table, row);
			FileCustomerAddress obj = JSON.toJavaObject(javaObject, FileCustomerAddress.class);
			if(RowState.NEW.equals(obj.getRowState())){
				dao.insert(obj);
			}
			if(RowState.DELETE.equals(obj.getRowState())){
				dao.delete(obj.getfID());
			}
			if(RowState.EDIT.equals(obj.getRowState())){
				FileCustomerAddress objNew = dao.update(obj);
				//返回+1后的version到前台BizData中进行刷新，使得前台的version与后台的一致。
				///////////////////////////////////////////////////////////////////////
				JSONObject jsonRow = new JSONObject();
				jsonRow.put("id", obj.getfID());
				jsonRow.put("version", objNew.getVersion());
				rows.add(jsonRow);
				//////////////////////////////////////////////////////////////////////
			}
		}
		
		data.put("rows", rows);
		
		return data;
	}
	
	
	@Override
	public JSONObject queryUNION(JSONObject data) throws Throwable {
		// TODO Auto-generated method stub
		return dao.queryUNION(data);
	}
	
	
	@Transactional
	@Override
	public int deleteByMasterID(String fMasterID){
		
		List<FileCustomerAddress> srds = dao.getByMasterID(fMasterID);
		for(FileCustomerAddress srd:srds){
			dao.delete(srd.getfID());;
		}
		return 0;
	}
	
	/*
	@Transactional
	@Override
	public void updateOrderID(String fID, String orderID, int numberOfActual) {
		// TODO Auto-generated method stub
		FileCustomerAddress obj = dao.getByID(fID);
		obj.setOrderID(orderID);
		obj.setNumberOfActual(numberOfActual);
		dao.update(obj);
	}
	*/
	
	@Transactional
	@Override
	public int setDefault(String rowID){
		FileCustomerAddress obj = dao.getByID(rowID);
		if(obj==null){
			return -1;
		}else{
			String fMasterID = obj.getfMasterID();
			List<FileCustomerAddress> srds = dao.getByMasterID(fMasterID);
			for(FileCustomerAddress srd:srds){
				//清除原来的默认
				if(srd.getiDefault()==1){
					srd.setiDefault(0);
					dao.update(srd);
				}
			}
			
			//设置新的默认
			obj.setiDefault(1);
			dao.update(obj);
			
		}
		return 0;
	}

	@Transactional
	@Override
	public int addAddress(JSONObject data, String cUsercode, String cUsername, String userId) {
		
//		SaOpperson person = SecurityService.getCurrentPerson();
		
		String fAddressName = data.getString("fAddressName");
		String fAddress = data.getString("fAddress");
		String fAddressDetail = data.getString("fAddressDetail");

		String fProvince = data.getString("fProvince");
		String fCity = data.getString("fCity");
		String fZone = data.getString("fZone");
		
		String contacts = data.getString("contacts");
		String mobilePhone = data.getString("mobilePhone");
		String fPhone = data.getString("fPhone");
		String email = data.getString("email");
		
		FileCustomerAddress obj = new FileCustomerAddress();
		obj.setfID(Utils.getUUID());
		
		obj.setfAddressName(fAddressName);
		obj.setfAddress(fAddress);
		obj.setfAddressDetail(fAddressDetail);
		
		obj.setfProvince(fProvince);
		obj.setfCity(fCity);
		obj.setfZone(fZone);
		
		obj.setContacts(contacts);
		obj.setMobilePhone(mobilePhone);
		obj.setfPhone(fPhone);
		obj.setEmail(email);
		
		obj.setfMasterID(userId);
		obj.setcUsercode(cUsercode);
		obj.setcUsername(cUsername);
		obj.setcDatetime(Utils.getCurrentDateTime());
		
		dao.insert(obj);
		
		//设置为缺省
		this.setDefault(obj.getfID());
		
		return 0;
	}
	
	@Override
	public JSONObject newData(JSONObject data) {
		return dao.create(data);
	}
	
	@Override
	public JSONObject deleteData(JSONObject param) {
		//System.out.println("fileFactoryCreate.param-->>"+param.toJSONString());
		JSONArray ids = param.getJSONArray("ids");
		for(int i=0;i<ids.size();i++){
			String id = ids.getString(i);
			//这里可以增加是否可删除的判断
			
			dao.delete(id);
		}

		JSONObject data = new JSONObject();
		data.put("ids", ids);
		
		JSONObject json = new JSONObject();
		json.put("code", 0);
		json.put("msg", "success");
		json.put("data", data);
		
		return json;
	}

	/*
	在@Transaction注解中定义noRollbackFor和RollbackFor指定某种异常是否回滚。 
	@Transactional(noRollbackFor=RuntimeException.class) 
	@Transactional(RollbackFor=Exception.class) 
	*/
	@Transactional
	@Override
	public JSONObject saveData(JSONObject param) {
		//Spring的事务管理默认只对出现运行期异常(java.lang.RuntimeException及其子类)进行回滚。 
		//如果一个方法抛出Exception或者Checked异常，Spring事务管理默认不进行回滚。 
		// JSON转换Table
		//System.out.println(object);
		JSONObject data;
		try {
			data = this.save(param);
					
			JSONObject json = new JSONObject();
			json.put("code", 0);
			json.put("msg", "success");
			json.put("data", data);
			
			return json;
			
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			log.info("开始打印ParseException");
			e.printStackTrace();
			log.info("e.getMessage()-->>"+e.getMessage());
			log.info("完成打印ParseException");
			
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", e.getMessage());
			
			return json;
		} 
	}
	
	/* (non-Javadoc)
	 * @see com.iune.erp.baseinfo.aaa#queryJDBC(com.alibaba.fastjson.JSONObject)
	 */
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	@Override
	public JSONObject queryData(JSONObject param){
		//在此层面（ServiceImpl）统一处理异常，此层面直接被controller调用，面对BizData
		
		try {
			JSONObject jsonTable = dao.query(param);
			
			JSONObject json = new JSONObject();
			json.put("code", 0);
			json.put("msg", "success");
			json.put("data", jsonTable);
			
			return json;
		} catch (SQLException e) {
			e.printStackTrace();
			
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", e.getMessage());
			return json;
		}
	}

	@Override
	public JSONObject validData(JSONObject param) {
		// TODO Auto-generated method stub
		return null;
	}
	
	

}
